import ImgUpload from "@/components/dataEntry/ImgUpload";
import { Button, Input, Popconfirm, Tooltip } from "antd";
import { ColumnProps, ColumnType } from "antd/lib/table";
import { cloneDeep } from "lodash";
import { forwardRef, ForwardRefRenderFunction, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { StyledArrowRow, StyledDownOutlined, StyledInnerTable, StyledOuterTable, StyledUpOutlined } from "../styled";

export interface ValueListItem {
	name: string;
	image: string | null;
	rowIndex: number;
}
export interface AttributeTableRecord {
	key: string;
	valueList: ValueListItem[];
}
interface AttributeTableProps {
	label?: "spu" | "sku选项";
	onChange?: (data: AttributeTableRecord[]) => void;
}
export interface AttributeTableRef {
	getData: () => AttributeTableRecord[];
	setData: (data: AttributeTableRecord[]) => void;
}
const AttributeTable: ForwardRefRenderFunction<AttributeTableRef, AttributeTableProps> = ({ label = "属性", onChange }, ref) => {
	const [dataSource, setDataSource] = useState<AttributeTableRecord[]>([]);
	useImperativeHandle(
		ref,
		() => ({
			getData: () => dataSource,
			setData: (data) => setDataSource(data),
		}),
		[dataSource]
	);
	useEffect(() => {
		onChange?.(dataSource);
	}, [dataSource]);
	const addAttributeRecord = useCallback(
		(index: number) => {
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource.splice(index, 0, { key: "", valueList: [{ name: "", image: null, rowIndex: index }] });
			setDataSource(copiedDataSource);
		},
		[dataSource]
	);
	const deleteAttributeRecord = useCallback(
		(index: number) => {
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource.splice(index, 1);
			setDataSource(
				copiedDataSource.map((item, rowIndex) => ({ ...item, valueList: item.valueList.map((item1) => ({ ...item1, rowIndex })) }))
			);
		},
		[dataSource]
	);
	const setValueItems = useCallback(
		(obj: Partial<Omit<ValueListItem, "rowIndex">> & { index: number; rowIndex: number }) => {
			const { index, rowIndex, ...remainingObj } = obj;
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource[rowIndex].valueList[index] = { ...copiedDataSource[rowIndex].valueList[index], ...remainingObj };
			setDataSource(copiedDataSource);
		},
		[dataSource]
	);
	const setKey = useCallback(
		(key: string, index: number) => {
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource[index].key = key;
			setDataSource(copiedDataSource);
		},
		[dataSource]
	);
	const addAttributeValue = useCallback(
		(rowIndex: number, index: number) => {
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource[rowIndex].valueList.splice(index, 0, { name: "", image: null, rowIndex });
			setDataSource(copiedDataSource);
		},
		[dataSource]
	);
	const deleteAttributeValue = useCallback(
		(rowIndex: number, index: number) => {
			const copiedDataSource = cloneDeep(dataSource);
			copiedDataSource[rowIndex].valueList.splice(index, 1);
			setDataSource(copiedDataSource);
		},
		[dataSource]
	);
	const moveInnerRecord = (rowIndex: number, index: number, position: -1 | 1) => {
		const copiedData = cloneDeep(dataSource);
		if (position === -1) {
			copiedData[rowIndex].valueList.splice(index - 1, 0, copiedData[rowIndex].valueList.splice(index, 1)[0]);
		} else {
			copiedData[rowIndex].valueList.splice(index, 0, copiedData[rowIndex].valueList.splice(index + 1, 1)[0]);
		}
		setDataSource(copiedData);
	};
	const innerColumns = useMemo<ColumnProps<ValueListItem>[]>(
		() => [
			{
				dataIndex: "name",
				width: 260,
				render: (_, { rowIndex }, index) => (
					<div>
						<StyledArrowRow>
							{index !== 0 && (
								<Tooltip title="向上移动">
									<StyledUpOutlined onClick={() => moveInnerRecord(rowIndex, index, -1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
						<Input
							placeholder={`请输入${label}值`}
							value={dataSource[rowIndex].valueList[index].name}
							onChange={(e) => setValueItems({ name: e.target.value, index, rowIndex })}
						/>
						<StyledArrowRow>
							{index !== dataSource[rowIndex].valueList.length - 1 && (
								<Tooltip title="向上移动">
									<StyledDownOutlined onClick={() => moveInnerRecord(rowIndex, index, 1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
					</div>
				),
			},
			{
				dataIndex: "image",
				width: 190,
				render: (_, { rowIndex }, index) => (
					<ImgUpload
						zoom={0.6}
						value={dataSource[rowIndex].valueList[index].image}
						onChange={(image) => setValueItems({ image: image as string, index, rowIndex })}
					/>
				),
			},
			{
				width: 120,
				render: (_, { rowIndex }, index) => (
					<div>
						<Tooltip title={`在下面添加${label}值`}>
							<Button
								type="primary"
								size="small"
								shape="circle"
								icon={<PlusOutlined />}
								onClick={() => addAttributeValue(rowIndex, index + 1)}
							/>
						</Tooltip>
						{dataSource[rowIndex].valueList.length > 1 && (
							<Popconfirm title={`确定删除${label}值吗？`} onConfirm={() => deleteAttributeValue(rowIndex, index)}>
								<Button size="small" className="ml-1" danger icon={<DeleteOutlined />} shape="circle" />
							</Popconfirm>
						)}
					</div>
				),
			},
		],
		[dataSource]
	);

	const moveRecord = (index: number, position: 1 | -1) => {
		const copiedData = cloneDeep(dataSource);
		copiedData[index + position].valueList = copiedData[index + position].valueList.map((item) => ({
			...item,
			rowIndex: item.rowIndex - position,
		}));
		const deleteRecord = copiedData.splice(index, 1)[0];
		deleteRecord.valueList = deleteRecord.valueList.map((item) => ({ ...item, rowIndex: item.rowIndex + position }));
		copiedData.splice(index + position, 0, deleteRecord);
		setDataSource(copiedData);
	};
	const columns = useMemo<ColumnProps<AttributeTableRecord>[]>(
		() => [
			{
				dataIndex: "key",
				width: 200,
				title: `${label}名`,
				render: (_, _1, index) => (
					<div>
						<StyledArrowRow>
							{index !== 0 && (
								<Tooltip title="向上移动">
									<StyledUpOutlined onClick={() => moveRecord(index, -1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
						<Input
							className="my-2"
							placeholder={`请输入${label}名`}
							value={dataSource[index].key}
							onChange={(e) => {
								setKey(e.target.value, index);
							}}
						/>

						<StyledArrowRow>
							{index !== dataSource.length - 1 && (
								<Tooltip title="向下移动" placement="bottom">
									<StyledDownOutlined onClick={() => moveRecord(index, 1)} />
								</Tooltip>
							)}
						</StyledArrowRow>
					</div>
				),
			},
			{
				dataIndex: "valueList",
				width: 500,
				title: (
					<div className="flex justify-between">
						<div style={{ width: "45%" }} className="text-left ml-4">
							{label}值
						</div>
						<div style={{ width: "35%" }} className="text-left ml-4">
							值图片
						</div>
						<div style={{ width: "20%" }}>值操作</div>
					</div>
				),
				render: (valueList, _, rowIndex) => (
					<div>
						<StyledInnerTable
							pagination={false}
							showHeader={false}
							columns={innerColumns as ColumnType<object>[]}
							dataSource={valueList.map((item: ValueListItem, index: number) => ({ ...item, key: `${rowIndex}-${index}` }))}
						/>
					</div>
				),
			},
			{
				title: `${label}操作`,
				width: 100,
				render: (_, _1, index) => (
					<div className="flex nowrap">
						<Tooltip title={`在下面添加${label}`}>
							<Button size="small" type="primary" onClick={() => addAttributeRecord(index + 1)}>
								添加
							</Button>
						</Tooltip>
						<Popconfirm title={`确定删除${label}吗`} onConfirm={() => deleteAttributeRecord(index)}>
							<Button className="ml-2" size="small" danger>
								删除
							</Button>
						</Popconfirm>
					</div>
				),
			},
		],
		[dataSource]
	);
	return (
		<div className="mt-8">
			<StyledOuterTable
				bordered
				{...(label === "spu" ? {} : { title: () => <h4 className="text-center">添加sku选项</h4> })}
				columns={columns as ColumnType<object>[]}
				dataSource={dataSource.map((item, index) => ({
					...item,
					key: index.toString(),
				}))}
				pagination={false}
			/>
			<Button size="small" shape="round" className="my-2" type="primary" onClick={() => addAttributeRecord(dataSource.length)}>
				添加{label}
			</Button>
		</div>
	);
};

export default forwardRef(AttributeTable);
